from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView, CreateView, DetailView

from . import models
from .models import Conversation2, Message2
from .forms import ConversationForm, MessageForm
from django.shortcuts import get_object_or_404


class ConversationListView(LoginRequiredMixin, ListView):
    model = Conversation2

    def get_queryset(self):
        return Conversation2.objects.filter(
            models.Q(participant1=self.request.user) |
            models.Q(participant2=self.request.user)
        )


class ConversationCreateView(LoginRequiredMixin, CreateView):
    form_class = ConversationForm
    template_name = 'chat/conversation_form.html'

    def form_valid(self, form):
        form.instance.participant1 = self.request.user
        return super().form_valid(form)

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs


class ConversationDetailView(LoginRequiredMixin, DetailView):
    model = Conversation2

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['form'] = MessageForm()
        return context

    def post(self, request, *args, **kwargs):
        form = MessageForm(request.POST)
        if form.is_valid():
            message = form.save(commit=False)
            message.conversation = self.get_object()
            message.sender = request.user
            message.save()
        return self.get(request, *args, **kwargs)

    def get_queryset(self):
        return Conversation2.objects.filter(
            models.Q(participant1=self.request.user) |
            models.Q(participant2=self.request.user)
        )